package com.cn.springcloudwechat.upload;

import com.cn.springcloudwechat.controller.base.BaseController;
import org.springframework.web.multipart.MultipartFile;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

public class FileUtil {
    public static String upload(MultipartFile file) throws IOException {
        String path = null;
            path =  BaseController.getRealPath();
            String fileName=file.getOriginalFilename().trim().replace(" ","");
            path += File.separator + fileName;
            long start=System.currentTimeMillis();
            System.out.println("*****************临时上传对象创建中*****************"+start);

            File tempFile = new File(path);
            if (!tempFile.getParentFile().exists()) {
                tempFile.getParentFile().mkdirs();
            }
            file.transferTo(tempFile);
        System.out.println("*****************临时对象创建完成*****************"+(System.currentTimeMillis()-start)+":ms");
            path = com.cn.springcloudwechat.upload.CosUtils.SimpleUploadFileFromLocal(path);
            tempFile.delete();
    return path;
    }

    /**
     * byte[]转文件
     * @param buf
     * @param filePath
     * @param fileName
     */
    public static void byte2File(byte[] buf, String filePath, String fileName)
    {
        filePath=BaseController.getRealPath();
        BufferedOutputStream bos = null;
        FileOutputStream fos = null;
        File file = null;
        try
        {
            File dir = new File(filePath);
            if (!dir.exists() && dir.isDirectory())
            {
                dir.mkdirs();
            }
            file = new File(filePath + File.separator + fileName);
            fos = new FileOutputStream(file);
            bos = new BufferedOutputStream(fos);
            bos.write(buf);
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            if (bos != null)
            {
                try
                {
                    bos.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
            if (fos != null)
            {
                try
                {
                    fos.close();
                }
                catch (IOException e)
                {
                    e.printStackTrace();
                }
            }
        }
    }
}
